package com.android.newsreader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
* An activity class to allow RSS feed URLs to 
* be added to news channels or existing feeds to changed
*/
public class InputFeedURL extends Activity {
	
	private RSSChannelProvider mDb4oHelper = null;

	private RSSChannel mFeedToEdit = null;
	private TextView mUrlInput = null;
	
	/** 
	 * Called when the activity is first created. 
	 * 
	 * Populates activity fields with the Channel's
	 *  Name, Category & URL (if present)
	 * 
	 * */
	public void onCreate(Bundle savedInstanceState) 
    {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.feed_edit);
        
        Intent startingIntent = getIntent();
        mFeedToEdit = (RSSChannel)startingIntent.getSerializableExtra("channel");
	    
        
        TextView channelView = (TextView) findViewById(R.id.channel_view);
        channelView.setText(mFeedToEdit.getName());
	    
        TextView catView = (TextView) findViewById(R.id.cat_view);
        catView.setText(mFeedToEdit.getCategory());
        
        mUrlInput = (TextView) findViewById(R.id.url_input);
        
        if (!mFeedToEdit.getURL().equalsIgnoreCase(""))
        	mUrlInput.setText(mFeedToEdit.getURL());
	    
        dbHelper();
        initialiseButtons();
    }
	
	/**
	 *  Sets up action listeners for buttons
	 *  on the activity 
	 * */
	private void initialiseButtons(){
    	Button cancelbutton = (Button) findViewById(R.id.cancel);
        
        cancelbutton.setOnClickListener(new Button.OnClickListener() 
        {
            public void onClick(View v) 
            {
            	finish();
            }
        }); 
        	
        Button saveButton = (Button) findViewById(R.id.save);
            
        saveButton.setOnClickListener(new Button.OnClickListener() 
            {
                public void onClick(View v) 
                {
                	mFeedToEdit.setURL(mUrlInput.getText().toString());
                	mDb4oHelper.store(mFeedToEdit);
                	finish();
                }
            });

    }
	
	
	
	/**
     * Create RSSChannelProvider instance
     */
     private RSSChannelProvider dbHelper() {
         if (mDb4oHelper == null) {
            mDb4oHelper = RSSChannelProvider.getInstance(this);
            mDb4oHelper.db();
         }
         
         return mDb4oHelper;
     } 
	
     /**
      * Close database before exiting the application
      */
      @Override
      protected void onPause() {
           super.onDestroy();
           if (mDb4oHelper != null)
        	   mDb4oHelper.close();
      }
      
      @Override
  	  protected void onResume() {
  		
  		super.onResume();
  		dbHelper();
  	  }

}
